package org.yang.database.minio.service.impl;


import io.minio.MinioClient;
import io.minio.PostPolicy;
import io.minio.errors.MinioException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.yang.common.core.exception.BaseException;
import org.yang.common.utils.string.StringUtils;
import org.yang.database.minio.callback.Callback;
import org.yang.database.minio.service.MinioService;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.ZonedDateTime;
import java.util.Map;

/**
 * Minio常用接口实现
 * @author: Islands
 * @description:
 * @version：v1.0
 * @date: 2024/8/27 20:28
 */

@Service
public class MinioServiceImpl implements MinioService {

    @Autowired
    private MinioClient minioClient;

    @Override
    public Map<String, String> signature(String bucketName, String fileName, Callback callback) throws BaseException {
        //设置凭证过期时间
        ZonedDateTime expirationDate= ZonedDateTime.now().plusMinutes(10);
        //创建一个凭证
        PostPolicy callbackPolicy;
        PostPolicy policy = new PostPolicy(bucketName,fileName, expirationDate);
        if(callback!=null){
            //回调:限制文件大小，单位是字节byte，也就是说可以设置如：只允许10M以内的文件上传;限制上传文件请求的ContentType等
           callbackPolicy = callback.run(policy);
        }else{
            callbackPolicy=policy;
        }
        try {
            // 生成凭证并返回
            return minioClient.presignedPostPolicy(callbackPolicy);
        } catch (MinioException | InvalidKeyException | IOException | NoSuchAlgorithmException e) {
            throw new BaseException(e.getMessage());
        }
    }
}
